package com.work.yshop.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.work.yshop.adapter.ArticleAdapter;
import com.work.yshop.databinding.FragmentAgriTechBinding;
import com.work.yshop.model.Article;
import com.work.yshop.mvp.contract.AgriTechContract;
import com.work.yshop.mvp.contract.LoginContract;
import com.work.yshop.mvp.presenter.AgriTechPresenter;
import com.work.yshop.ui.activity.AddArticleActivity;
import com.work.yshop.ui.activity.ArticleDetailActivity;
import com.work.yshop.ui.activity.PublishActivity;
import com.work.yshop.utils.UserSession;

import java.util.ArrayList;
import java.util.List;

/**
 * 农技页面Fragment
 */
public class AgriTechFragment extends Fragment implements AgriTechContract.View {

    private static final String TAG = "AgriTechFragment";
    private FragmentAgriTechBinding binding;
    private ArticleAdapter adapter;
    private AgriTechContract.Presenter presenter;
    
    // 文章分类，确保与TabLayout中的标签文本一致
    private final String[] categories = {"推荐", "种植技术", "病虫防治", "农业科学", "视频教学"};

    public static AgriTechFragment newInstance() {
        return new AgriTechFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentAgriTechBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        Log.d(TAG, "创建AgriTechFragment");
        
        // 初始化Presenter
        presenter = new AgriTechPresenter(requireContext());
        ((AgriTechPresenter) presenter).attachView(this);
        
        // 初始化视图
        initViews();
        
        // 设置事件监听
        setupListeners();
        
        // 加载文章列表
        presenter.loadArticles();
        
        Log.d(TAG, "AgriTechFragment初始化完成");
    }
    
    private void initViews() {
        // 设置RecyclerView
        Log.d(TAG, "初始化RecyclerView");
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        binding.recyclerArticles.setLayoutManager(layoutManager);
        
        // 确保适配器不为空
        if (adapter == null) {
            adapter = new ArticleAdapter(requireContext());
        }
        binding.recyclerArticles.setAdapter(adapter);
        
        // 无论是买家还是卖家，都显示添加按钮
        binding.fabAdd.setVisibility(View.VISIBLE);
        
        Log.d(TAG, "RecyclerView适配器已设置");
    }
    
    private void setupListeners() {
        // 下拉刷新
        binding.swipeRefresh.setOnRefreshListener(() -> {
            presenter.refreshArticles();
        });
        
        // 添加按钮点击事件
        binding.fabAdd.setOnClickListener(v -> {
            // 无论是买家还是卖家，都可以添加文章
            if (UserSession.getInstance().getUserType() == LoginContract.USER_TYPE_SELLER) {
                // 卖家直接进入添加文章页面
                Intent intent = new Intent(requireContext(), AddArticleActivity.class);
                startActivity(intent);
            } else {
                // 买家也可以添加文章
                Intent intent = new Intent(requireContext(), AddArticleActivity.class);
                startActivity(intent);
            }
        });
        
        // 文章点击事件
        adapter.setOnItemClickListener(position -> {
            Article article = adapter.getItem(position);
            presenter.onArticleClick(article);
        });
        
        // 分类选项卡选择事件
        binding.tabLayout.addOnTabSelectedListener(new com.google.android.material.tabs.TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(com.google.android.material.tabs.TabLayout.Tab tab) {
                int position = tab.getPosition();
                
                Log.d(TAG, "选择了标签: " + position + ", 文本: " + (tab.getText() != null ? tab.getText() : "null"));
                
                if (position == 0) {
                    // 第一个标签(推荐)显示所有文章
                    Log.d(TAG, "加载所有文章(推荐)");
                    presenter.loadArticles();
                } else if (position >= 0 && position < categories.length) {
                    // 其他标签按分类筛选
                    String category = categories[position];
                    Log.d(TAG, "加载分类文章: " + category);
                    presenter.loadArticlesByCategory(category);
                }
            }

            @Override
            public void onTabUnselected(com.google.android.material.tabs.TabLayout.Tab tab) {
                // 不需要处理
            }

            @Override
            public void onTabReselected(com.google.android.material.tabs.TabLayout.Tab tab) {
                // 重新选择相同标签时刷新
                onTabSelected(tab);
            }
        });
    }
    
    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "AgriTechFragment onResume");
        
        // 检查适配器和RecyclerView状态
        if (adapter == null || binding.recyclerArticles.getAdapter() == null) {
            Log.d(TAG, "onResume: 重新初始化视图");
            initViews();
        }
        
        // 刷新数据
        presenter.refreshArticles();
    }

    @Override
    public void showLoading() {
        if (isAdded()) {
            binding.swipeRefresh.setRefreshing(true);
        }
    }

    @Override
    public void hideLoading() {
        if (isAdded()) {
            binding.swipeRefresh.setRefreshing(false);
        }
    }

    @Override
    public void showArticles(List<Article> articles) {
        if (!isAdded()) return;
        
        Log.d(TAG, "显示文章列表: " + articles.size() + "篇");
        
        // 确保UI更新在主线程
        requireActivity().runOnUiThread(() -> {
            binding.recyclerArticles.setVisibility(View.VISIBLE);
            binding.emptyView.setVisibility(View.GONE);
            // 确保适配器不为空
            if (adapter == null) {
                Log.d(TAG, "适配器为空，重新创建");
                adapter = new ArticleAdapter(requireContext());
                binding.recyclerArticles.setAdapter(adapter);
            }
            
            adapter.setData(articles);
            Log.d(TAG, "适配器数据已更新");
        });
    }

    @Override
    public void showEmptyView() {
        if (isAdded()) {
            requireActivity().runOnUiThread(() -> {
                binding.recyclerArticles.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
                // 同样清空适配器数据，防止旧数据残留
                if (adapter != null) {
                    adapter.setData(new ArrayList<>());
                }
            });
        }
    }

    @Override
    public void showError(String message) {
        if (isAdded()) {
            Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void navigateToArticleDetail(Article article) {
        if (isAdded()) {
            Intent intent = new Intent(requireContext(), ArticleDetailActivity.class);
            intent.putExtra("article_id", article.getId());
            startActivity(intent);
        }
    }

    @Override
    public void navigateToAddArticle() {
        if (isAdded()) {
            // 无论是买家还是卖家，都可以添加文章
            Intent intent = new Intent(requireContext(), AddArticleActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (presenter != null) {
            presenter.detachView();
        }
        binding = null;
    }
} 